package cn.xiangxiang.controller.file;

import cn.xiangxiang.common.Utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class Upload {

    @RequestMapping("/uploadimg")
    public String uploadImg(MultipartFile file, String dir) throws IOException {

        // String filename = file.getOriginalFilename();
        // System.out.println("filename = " + filename);
/*
        String realPath = session.getServletContext().getRealPath("/img");
        realPath= realPath+"/"+dir;

        File dirFile = new File(realPath);

        if(!dirFile.exists()){
            dirFile.mkdirs();
        }

        String imgFileName = file.getOriginalFilename();
        imgFileName = Utils.getuuid(32)+imgFileName;//brand1.jpg

        File newfile = new File(dirFile, imgFileName);
        try {
            file.transferTo(newfile);
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI4G1TQSPkaEzYq1rngZMY";
        String accessKeySecret = "y63YdnU39d3fsXTJHrMPJFj7lt1hFs";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String imgFileName = file.getOriginalFilename();
        imgFileName = Utils.getuuid(32) + imgFileName;//brand1.jpg

        // 创建PutObjectRequest对象。
        //PutObjectRequest putObjectRequest = new PutObjectRequest("xiangxiang511", imgFileName,new File(file.getInputStream().toString()) );

        // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。

        String dirFileName = dir + "/" + imgFileName;

        ossClient.putObject("xiangxiang511", dirFileName, file.getInputStream());

        // 关闭OSSClient。
        ossClient.shutdown();

        return "https://xiangxiang511.oss-cn-hangzhou.aliyuncs.com/" + dirFileName;
    }

}
